﻿using System;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Collections;
using System.Net.Mail;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace CSharp.Common.Http
{
    public class Email
    {
        public static bool SendEmailUseGmail(EmailInformation emailInfo)
        {
            System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
            Regex RegEmail = new Regex(@"^[\w-]+@[\w-]+\.(com|net|org|edu|mil|tv|biz|info)$");
            if ((emailInfo.ToEmailAddress != null) && (emailInfo.ToEmailAddress.Count > 0))
            {
                foreach (var item in emailInfo.ToEmailAddress)
                {
                    if (RegEmail.Match(item).Success)
                    {
                        message.To.Add(item);
                    }
                }
            }

            if (System.IO.File.Exists(emailInfo.AttachmentPath))
            {
                message.Attachments.Add(new Attachment(emailInfo.AttachmentPath));
            }

            message.From = new MailAddress(emailInfo.GmailUsername, emailInfo.GmailUsername.Substring(0, emailInfo.GmailUsername.IndexOf('@')), System.Text.Encoding.UTF8);
          
            message.Subject = emailInfo.EmailSubject;
            message.SubjectEncoding = System.Text.Encoding.UTF8;
            message.Body = emailInfo.EmailBody;
            message.BodyEncoding = System.Text.Encoding.UTF8;
            message.IsBodyHtml = false;
            message.Priority = MailPriority.High;
            SmtpClient client = new SmtpClient();

            if (RegEmail.Match(emailInfo.GmailUsername).Success)
            {
                client.Credentials = new System.Net.NetworkCredential(emailInfo.GmailUsername, emailInfo.GmailPassword);
            
            }

            client.Port = 587;
            client.Host = "smtp.gmail.com";
            client.EnableSsl = true;
            object userState = message;
            try
            {
                client.Send(message);              
                return true;
            }
            catch (System.Net.Mail.SmtpException ex)
            {
                return false;
            }


        }


    }
}